package cn.touna.jss.modules.custom.carmodel.synctask;

import cn.touna.jss.modules.credit.entity.TaskRecordEntity;
import cn.touna.jss.modules.credit.mapper.TaskRecordEntityMapper;
import cn.touna.jss.modules.custom.carmodel.dto.TaskInfo;
import com.alibaba.fastjson.JSONObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.Date;

/**
 * Created by Steve.Tao on 2017/11/17.
 */
@Service
public class CarModelSyncTaskExecutor {

    /**
     * 任务：同步车型车系
     */
    public final static String TASK_SYNC_CAR_MODEL = "SyncCarModel";

    private static final Logger logger = LogManager.getLogger();

    @Autowired
    private TaskRecordEntityMapper taskRecordEntityMapper;

    @Autowired
    private Car300SyncModelService car300SyncModelService;
    @Autowired
    private JzgSyncModelService jzgSyncModelService;

    public void doTask(String taskId, TaskInfo taskInfo) {
        logger.info("【同步车系】开始同步，taskId={},taskInfo:{}", taskId, JSONObject.toJSONString(taskInfo));
        doTask1(taskId, taskInfo);
        logger.info("【同步车系】完成同步，taskId={},taskInfo:{}", taskId, JSONObject.toJSONString(taskInfo));
    }

    private void doTask1(String taskId, TaskInfo taskInfo) {
        try {
            //开始任务
            insertNewTask(taskId, taskInfo);
            //执行任务
            SyncModelResult result1 = car300SyncModelService.refreshModel(taskId);
            SyncModelResult result2 = jzgSyncModelService.refreshModel(taskId);
            JSONObject msgObj = new JSONObject();
            msgObj.put("car300", result1);
            msgObj.put("jingzhengu", result2);
            String msg = msgObj.toJSONString();
            if (result1.isSuccess() || result2.isSuccess()) {  //成功，无异常
                //完成任务
                completeTask(taskId, taskInfo.getType(), 2, msg);
            } else {  //有异常情况，有可能局部成功
                completeTask(taskId, taskInfo.getType(), 3, msg);
            }
        } catch (Exception e) {
            completeTask(taskId, taskInfo.getType(), 3, e.getMessage());
            logger.error("执行任务失败，", e);
        }
    }

    public void test() {
        String taskNo = LocalDate.now().toString();
        TaskInfo taskInfo = new TaskInfo();
        taskInfo.setType(CarModelSyncTaskExecutor.TASK_SYNC_CAR_MODEL);
        taskInfo.setDesc("同步车型库，包括车300和精真估");
        insertNewTask(taskNo, taskInfo);
        completeTask(taskNo, taskInfo.getType(), 2, "xx");
    }

    private void insertNewTask(String taskNo, TaskInfo taskInfo) {
        TaskRecordEntity recordEntity = new TaskRecordEntity();
        recordEntity.setBeginTime(new Date());
        if (taskInfo.getDesc() == null)
            taskInfo.setDesc("");
        recordEntity.setDetail(taskInfo.getDesc());
        recordEntity.setTaskNo(taskNo);
        recordEntity.setTaskType(taskInfo.getType());
        recordEntity.setTaskStatus((byte) 1);
        taskRecordEntityMapper.insertNewTask(recordEntity);
    }

    private void completeTask(String taskNo, String taskType, int status, String message) {
        TaskRecordEntity recordEntity = new TaskRecordEntity();
        recordEntity.setTaskNo(taskNo);
        recordEntity.setTaskType(taskType);
        recordEntity.setTaskStatus((byte) status);
        recordEntity.setEndTime(new Date());
        if (message == null)
            message = "";
        if (message.length() > 1000)
            message = message.substring(0, 999);
        System.out.println(message);
        recordEntity.setMessage(message);
        taskRecordEntityMapper.completeTask(recordEntity);
    }
}
